import { Component, OnInit, ViewChild } from '@angular/core';
import { Helper } from '../../common/index';
import { ControlBase } from '../../../shared/dynamicform/controlbase';
import { TextBox } from '../../../shared/dynamicform/textbox-control';
import { EmailValidator, PasswordValidator } from '../../../shared/dynamicform/my-validator';
import { FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs/Rx';
import { SessionService } from '../../../services/session-service';
import { AuthService } from '../../../services/auth-service';
import { UserService } from '../../../services/user-service';
import { MdlSnackbarService, MdlDialogService } from '@angular-mdl/core';
import { Router } from '@angular/router';
import { Location } from '@angular/common';

@Component({
	selector: 'app-changepass',
	templateUrl: './changepass.component.html',
	styleUrls: ['./changepass.component.scss'],
	providers: [AuthService, SessionService, MdlDialogService, UserService, MdlSnackbarService]
})
export class ChangepassComponent implements OnInit {

	formInputs: ControlBase<any>[];

	formControls: any;

	@ViewChild('changePassForm')
	changePassForm;

	@ViewChild('failAlert') alert;

	redirectPage: { [role: string]: string } = {
		'管理员': '/project',
		'物业': '/company',
		'hr': '/user'
	};

	constructor(
		private _router: Router,
		private _authService: AuthService,
		private _sessionService: SessionService,
		private _location: Location,
		private _dialogService: MdlDialogService,
		private _userService: UserService,
		private _snackService: MdlSnackbarService
	) { }

	ngOnInit() {
		this.formControls = this._setForm(null);
	}

	private _setForm(data: any): any {

		this.formInputs = [
			new TextBox({
				type: 'password',
				key: 'oldPassword',
				label: '旧密码',
				value: '',
				required: true,
				order: 0,
				groupId: 0,
				validators: Validators.required
			}),
			new TextBox({
				type: 'password',
				key: 'newPassword',
				label: '新密码(字母和数字组合，不包含特殊符号)',
				value: '',
				required: true,
				order: 1,
				groupId: 1,
				require: true,
				validators: [Validators.required, PasswordValidator()]
			}),
			new TextBox({
				type: 'password',
				key: 'passwordConfirm',
				label: '新密码确认',
				value: '',
				required: true,
				order: 1,
				groupId: 2,
				require: true,
				validators: [Validators.required, PasswordValidator()]
			})
		];
		return Helper.setGroupForm(this.formInputs);
	}
	async change(df: any) {

		let form = <FormGroup>df.form;
		if (!form.valid) {
			return false;
		}
		let formVal = this.changePassForm.form.value;
		if (formVal.newPassword !== formVal.passwordConfirm) {
			this._dialogService.alert('两次密码输入不一致');
			return false;
		}
		try {
			let userId = this._sessionService.getCurrentUser().id;
			await this._userService.changePassword(userId, formVal.oldPassword, formVal.newPassword).toPromise();
			this._snackService.showToast('修改成功', 2000).subscribe(() => {
				this._sessionService.destroy();
				this._router.navigate(['/login']);
			});
		}
		catch (e) {
			if (e.status === 401) {
				this._sessionService.destroy();
				this._router.navigate(['/login']);
				return;
			}
			this.alert.show('原密码不正确，请核对后重新输入！');
		}
		finally {
		}
	}
	public onLoadFormData(form) {
		console.log(form);
	}

}
